package com.middlegroup.subjectpay.service.impl;

import com.middlegroup.common.enums.ChannelCode;
import com.middlegroup.common.enums.ServiceType;
import com.middlegroup.common.exception.ErrorMsg;
import com.middlegroup.common.model.TransResult;
import com.middlegroup.subjectpay.dto.BindCardDto;
import com.middlegroup.subjectpay.entity.ThirdProtocolApply;
import com.middlegroup.subjectpay.entity.ThirdProtocolBindCard;
import com.middlegroup.subjectpay.entity.ThirdProtocolBindRecord;
import com.middlegroup.subjectpay.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 *
 * @author pc
 * @date 2019/1/14
 */
@Service
@Slf4j
public class BindCardServiceImpl implements BindCardService {
    @Resource
    private ThirdProtocolBindRecordService thirdProtocolBindRecordService;
    @Resource
    private ThirdProtocolBindCardService thirdProtocolBindCardService;
    @Resource
    private UcfpayService ucfpayService;
    @Resource
    private ThirdProtocolApplyService thirdProtocolApplyService;
    @Resource
    private KjtpayService KjtpayService;

    @Override
    public TransResult bindCard(BindCardDto bindCardDto) {
        TransResult transResult = new TransResult();
        transResult.setBillNo(bindCardDto.getBillNo());
        transResult.setMerchantBillNo(bindCardDto.getMerchantBillNo());
        transResult.setTransStatus(0);
        transResult.setMsg("绑卡处理中");

        if(StringUtils.equals(ServiceType.BINDCARDAPPLY.name(),bindCardDto.getServiceType())){
            //1:绑卡申请
            if(StringUtils.isBlank(bindCardDto.getName())){
                transResult.setMsg(ErrorMsg.EMPTY_NAME);
                transResult.setTransStatus(2);
                return transResult;
            }
            if(StringUtils.isBlank(bindCardDto.getCardNo())){
                transResult.setMsg(ErrorMsg.EMPTY_CREDNO);
                transResult.setTransStatus(2);
                return transResult;
            }
            if(StringUtils.isBlank(bindCardDto.getIdCard())){
                transResult.setMsg(ErrorMsg.EMPTY_IDCARD);
                transResult.setTransStatus(2);
                return transResult;
            }
            if(StringUtils.isBlank(bindCardDto.getPhone())){
                transResult.setMsg(ErrorMsg.EMPTY_CARDPHONE);
                transResult.setTransStatus(2);
                return transResult;
            }
            if(null==bindCardDto.getChannelCode()){
                transResult.setMsg(ErrorMsg.EMPTY_CHANNELCODE);
                transResult.setTransStatus(2);
                return transResult;
            }

        }else if(StringUtils.equals(ServiceType.BINDCARDCONFIRM.name(),bindCardDto.getServiceType())){
            //2：绑卡确认
            if(StringUtils.isBlank(bindCardDto.getSmsCode())){
                transResult.setMsg(ErrorMsg.EMPTY_SMSCODE);
                transResult.setTransStatus(2);
                return transResult;
            }
        }else if(StringUtils.equals(ServiceType.RESENDSMS.name(),bindCardDto.getServiceType())){
            // 3：重发验证码
        }else {
            //类型未定义，异常
            transResult.setMsg(ErrorMsg.NO_TYPE);
            transResult.setTransStatus(2);
            return transResult;
        }

        ThirdProtocolBindRecord thirdProtocolBindRecord=null;
        if(StringUtils.equals(ServiceType.BINDCARDAPPLY.name(),bindCardDto.getServiceType())) {
            //1:绑卡申请
            thirdProtocolBindRecord = new ThirdProtocolBindRecord();
            thirdProtocolBindRecord.setSubjectCode(bindCardDto.getSubjectCode());
            thirdProtocolBindRecord.setChannelCode(bindCardDto.getChannelCode().getCode());
            thirdProtocolBindRecord.setMerchantBillNo(bindCardDto.getMerchantBillNo());
            thirdProtocolBindRecord.setBillNo(bindCardDto.getBillNo());
            thirdProtocolBindRecord.setCardNo(bindCardDto.getCardNo());
            thirdProtocolBindRecord.setPhone(bindCardDto.getPhone());
            thirdProtocolBindRecord.setName(bindCardDto.getName());
            thirdProtocolBindRecord.setIdCard(bindCardDto.getIdCard());
            thirdProtocolBindRecord.setStatus(0);

            boolean rt = false;
            try {
                rt = thirdProtocolBindRecordService.insert(thirdProtocolBindRecord);
            }catch (Exception e){
                log.error("插入主体端协议绑卡记录表(t_third_protocol_bind_record)失败,bindCardDto：{},error:{}",bindCardDto,e);
            }

            if (!rt) {
                //插入失败
                transResult.setMsg("插入主体端出款订单表(t_third_protocol_bind_record)失败:"+bindCardDto.getBillNo());
                transResult.setTransStatus(2);
                return transResult;
            }

        }else {
            //绑卡确认或重发短信验证码
            ThirdProtocolBindRecord thirdProtocolBindRecordFind = new ThirdProtocolBindRecord();
            thirdProtocolBindRecordFind.setSubjectCode(bindCardDto.getSubjectCode());
            thirdProtocolBindRecordFind.setMerchantBillNo(bindCardDto.getMerchantBillNo());
            thirdProtocolBindRecordFind.setBillNo(bindCardDto.getBillNo());

            thirdProtocolBindRecord=thirdProtocolBindRecordService.getLastOne(thirdProtocolBindRecordFind);
            boolean flag=null==thirdProtocolBindRecord || (null!=thirdProtocolBindRecord && 1==thirdProtocolBindRecord.getStatus());
            if(flag){
                transResult.setMsg("未找到该订单或订单状态已确认！");
                transResult.setTransStatus(2);
                return transResult;
            }
        }

        bindCardDto.setValidCode(thirdProtocolBindRecord.getValidCode());
        ChannelCode channelCode=ChannelCode.valueOf(thirdProtocolBindRecord.getChannelCode());
        /**
         * 此处一定要注意，调用第三方渠道接口必须返回TransResult，不可为空，且保证异常在接口中已处理
         */
        switch (channelCode){
            case CH3333331:
                try{
                    //TODO 调用第三方通道接口：先锋支付协议绑卡
                    if(StringUtils.equals(ServiceType.BINDCARDAPPLY.name(),bindCardDto.getServiceType())){
                        //绑卡申请
                        transResult =ucfpayService.bindcardApply(bindCardDto);
                    }else if(StringUtils.equals(ServiceType.BINDCARDCONFIRM.name(),bindCardDto.getServiceType())){
                        //绑卡确认
                        transResult =ucfpayService.bindcardConfirm(bindCardDto);
                    }else if(StringUtils.equals(ServiceType.RESENDSMS.name(),bindCardDto.getServiceType())){
                        //重发短信验证码
                        transResult =ucfpayService.reSendSms(bindCardDto);
                    }
                }catch (Exception e){
                    log.error("CH3333331第三方通道绑卡接口调用失败,bindCardDto:{},error:{}",bindCardDto,e);
                }
                break;
            case CH3333332:
                try{
                    //TODO 调用第三方通道接口：快捷通协议支付绑卡
                    if(StringUtils.equals(ServiceType.BINDCARDAPPLY.name(),bindCardDto.getServiceType())){
                        //绑卡申请
                        transResult =KjtpayService.bindcardApply(bindCardDto);
                    }else if(StringUtils.equals(ServiceType.BINDCARDCONFIRM.name(),bindCardDto.getServiceType())){
                        //绑卡确认
                        transResult =KjtpayService.bindcardConfirm(bindCardDto);
                    }else if(StringUtils.equals(ServiceType.RESENDSMS.name(),bindCardDto.getServiceType())){
                        //重发短信验证码
                        transResult =KjtpayService.reSendSms(bindCardDto);
                    }
                }catch (Exception e){
                    log.error("CH3333331第三方通道绑卡接口调用失败,bindCardDto:{},error:{}",bindCardDto,e);
                }
                break;
            case EMPTY0000003:
                try{
                    //TODO 模拟渠道：协议支付绑卡
                    if(StringUtils.equals(ServiceType.BINDCARDAPPLY.name(),bindCardDto.getServiceType())){
                        //绑卡申请
                        transResult =new TransResult(bindCardDto.getBillNo(),bindCardDto.getMerchantBillNo(),1,"模拟绑卡渠道绑卡申请成功",System.currentTimeMillis());
                    }else if(StringUtils.equals(ServiceType.BINDCARDCONFIRM.name(),bindCardDto.getServiceType())){
                        //绑卡确认
                        String protocolNo= UUID.randomUUID().toString().replaceAll("-","");
                        transResult =new TransResult(bindCardDto.getBillNo(),bindCardDto.getMerchantBillNo(),1,"模拟绑卡渠道绑卡确认成功",protocolNo);
                    }else if(StringUtils.equals(ServiceType.RESENDSMS.name(),bindCardDto.getServiceType())){
                        //重发短信验证码
                        transResult =new TransResult(bindCardDto.getBillNo(),bindCardDto.getMerchantBillNo(),1,"模拟绑卡渠道重发短信验证码成功",System.currentTimeMillis());
                    }
                }catch (Exception e){
                    log.error("EMPTY0000003第三方通道绑卡接口调用失败,bindCardDto:{},error:{}",bindCardDto,e);
                }
                break;
            default:
                transResult.setTransStatus(2);
                transResult.setMsg("未找到相应channelCode!");
        }

        //是否绑卡成功
        boolean ifBindCardSuccess = (StringUtils.equals(ServiceType.BINDCARDCONFIRM.name(),bindCardDto.getServiceType()) && null != transResult.getTransStatus() && 1==transResult.getTransStatus().intValue() && StringUtils.isNotBlank(transResult.getProtocolNo()));
        if(ifBindCardSuccess) {
            //TODO 确认绑卡成功，存起来
            ThirdProtocolBindCard thirdProtocolBindCardFind=new ThirdProtocolBindCard();
            thirdProtocolBindCardFind.setSubjectCode(thirdProtocolBindRecord.getSubjectCode());
            thirdProtocolBindCardFind.setChannelCode(thirdProtocolBindRecord.getChannelCode());
            thirdProtocolBindCardFind.setCardNo(thirdProtocolBindRecord.getCardNo());
            ThirdProtocolBindCard thirdProtocolBindCard=thirdProtocolBindCardService.getLastOne(thirdProtocolBindCardFind);

            if(null==thirdProtocolBindCard){
                thirdProtocolBindCard=new ThirdProtocolBindCard();
                thirdProtocolBindCard.setSubjectCode(thirdProtocolBindRecord.getSubjectCode());
                thirdProtocolBindCard.setChannelCode(thirdProtocolBindRecord.getChannelCode());
                thirdProtocolBindCard.setCardNo(thirdProtocolBindRecord.getCardNo());
                thirdProtocolBindCard.setPhone(thirdProtocolBindRecord.getPhone());
                thirdProtocolBindCard.setName(thirdProtocolBindRecord.getName());
                thirdProtocolBindCard.setIdCard(thirdProtocolBindRecord.getIdCard());
                thirdProtocolBindCard.setProtocolNo(transResult.getProtocolNo());
                thirdProtocolBindCard.setStatus(1);
                boolean falg=false;
                try {
                    falg=thirdProtocolBindCardService.insert(thirdProtocolBindCard);
                }catch (Exception e){
                    log.error("插入协议绑卡成功记录表(t_third_protocol_bind_card)失败,thirdProtocolBindCard：{},error:{}",thirdProtocolBindCard,e);
                }
                if(!falg){
                    transResult.setTransStatus(2);
                    transResult.setMsg("插入协议绑卡成功记录表失败");
                }
            }else {
                thirdProtocolBindCard.setPhone(thirdProtocolBindRecord.getPhone());
                thirdProtocolBindCard.setName(thirdProtocolBindRecord.getName());
                thirdProtocolBindCard.setIdCard(thirdProtocolBindRecord.getIdCard());
                thirdProtocolBindCard.setProtocolNo(transResult.getProtocolNo());
                thirdProtocolBindCard.setStatus(1);
                boolean falg=false;
                try {
                    falg=thirdProtocolBindCardService.updateById(thirdProtocolBindCard);
                }catch (Exception e){
                    log.error("更新协议绑卡成功记录表(t_third_protocol_bind_card)失败,thirdProtocolBindCard：{},error:{}",thirdProtocolBindCard,e);
                }
                if(!falg){
                    transResult.setTransStatus(2);
                    transResult.setMsg("更新协议绑卡成功记录表失败");
                }
            }
        }

        //是否更新绑卡记录表状态
        //是否更新绑卡记录表的validCode字段（例如快捷通协议绑卡申请和重发短信验证码的时候，返回的token_id要记下来，绑卡确认的时候使用）
        boolean ifUpdateBindCard = StringUtils.isNotBlank(transResult.getValidCode());
        boolean ifUpdateBindCardStatus = (StringUtils.equals(ServiceType.BINDCARDCONFIRM.name(),bindCardDto.getServiceType()) && null != transResult && null != transResult.getTransStatus() && (transResult.getTransStatus().intValue()==1 || transResult.getTransStatus().intValue()==2)) || (StringUtils.equals(ServiceType.BINDCARDAPPLY.name(),bindCardDto.getServiceType()) && null != transResult && null != transResult.getTransStatus() && transResult.getTransStatus().intValue()==2);
        if (ifUpdateBindCard || ifUpdateBindCardStatus){
            if (ifUpdateBindCard){
                thirdProtocolBindRecord.setValidCode(transResult.getValidCode());
            }
            if (ifUpdateBindCardStatus){
                thirdProtocolBindRecord.setStatus(transResult.getTransStatus());
            }
            thirdProtocolBindRecordService.updateById(thirdProtocolBindRecord);
        }

        return transResult;
    }

    @Override
    public String saveProtocolNo(ThirdProtocolApply thirdProtocolApply){
        //查询绑卡申请表，看是否有记录
        ThirdProtocolApply thirdProtocolApplyFoud=thirdProtocolApplyService.getLastOne(thirdProtocolApply);
        if(null==thirdProtocolApplyFoud){
            return null;
        }

        ThirdProtocolBindCard thirdProtocolBindCardFind=new ThirdProtocolBindCard();
        thirdProtocolBindCardFind.setSubjectCode(thirdProtocolApplyFoud.getSubjectCode());
        thirdProtocolBindCardFind.setChannelCode(thirdProtocolApplyFoud.getChannelCode());
        thirdProtocolBindCardFind.setCardNo(thirdProtocolApplyFoud.getCardNo());
        ThirdProtocolBindCard thirdProtocolBindCard=thirdProtocolBindCardService.getLastOne(thirdProtocolBindCardFind);

        if(null==thirdProtocolBindCard){
            thirdProtocolBindCard=new ThirdProtocolBindCard();
            thirdProtocolBindCard.setSubjectCode(thirdProtocolApplyFoud.getSubjectCode());
            thirdProtocolBindCard.setChannelCode(thirdProtocolApplyFoud.getChannelCode());
            thirdProtocolBindCard.setCardNo(thirdProtocolApplyFoud.getCardNo());
            thirdProtocolBindCard.setPhone(thirdProtocolApplyFoud.getPhone());
            thirdProtocolBindCard.setName(thirdProtocolApplyFoud.getName());
            thirdProtocolBindCard.setIdCard(thirdProtocolApplyFoud.getIdCard());
            //身份证号作为协议号
            thirdProtocolBindCard.setProtocolNo(thirdProtocolApplyFoud.getIdCard());
            thirdProtocolBindCard.setStatus(1);
            try {
                thirdProtocolBindCardService.insert(thirdProtocolBindCard);
            }catch (Exception e){
                log.error("插入协议绑卡成功记录表(t_third_protocol_bind_card)失败,thirdProtocolBindCard：{},error:{}",thirdProtocolBindCard,e);
            }
        }else {
            thirdProtocolBindCard.setPhone(thirdProtocolApplyFoud.getPhone());
            thirdProtocolBindCard.setName(thirdProtocolApplyFoud.getName());
            thirdProtocolBindCard.setIdCard(thirdProtocolApplyFoud.getIdCard());
            //身份证号作为协议号
            thirdProtocolBindCard.setProtocolNo(thirdProtocolApplyFoud.getIdCard());
            thirdProtocolBindCard.setStatus(1);
            try {
                thirdProtocolBindCardService.updateById(thirdProtocolBindCard);
            }catch (Exception e){
                log.error("更新协议绑卡成功记录表(t_third_protocol_bind_card)失败,thirdProtocolBindCard：{},error:{}",thirdProtocolBindCard,e);
            }
        }

        //更新绑卡申请记录表状态为成功
        thirdProtocolApplyFoud.setStatus(1);
        thirdProtocolApplyService.updateById(thirdProtocolApply);

        return thirdProtocolBindCard.getProtocolNo();
    }
}
